package com.eos.control.action.report.commission;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.eos.business.service.SysCommissionBusinessService;
import com.eos.common.tool.ConstantTool;
import com.eos.common.tool.ObjectUtils;
import com.eos.control.action.base.AbstractBaseAction;
import com.eos.orm.mybatis.model.BrokerageTempDetail;
import com.hf.utils.StringUtil;

public class SaveCommissionExcelAction extends AbstractBaseAction {
	private static final long serialVersionUID = 5588138205948153105L;
	private Integer customerId;
	private File excelFile; // 上传的文件
	private String excelFileFileName; // 保存原始文件名
	private String allowedTypes;
	
	 
	public File getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(File excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelFileFileName() {
		return excelFileFileName;
	}

	public void setExcelFileFileName(String excelFileFileName) {
		this.excelFileFileName = excelFileFileName;
	}
	
	public void setCustomerId(Integer customerId) {
		this.customerId = customerId;
	}

	// 判断文件类型
	public Workbook createWorkBook(InputStream is) throws IOException {
		if (excelFileFileName.toLowerCase().endsWith("xls")) {
			return new HSSFWorkbook(is);
		}
		if (excelFileFileName.toLowerCase().endsWith("xlsx")) {
			return new XSSFWorkbook(is);
		}
		return null;
	}

	public void setAllowedTypes(String allowedTypes) {
		this.allowedTypes = allowedTypes;
	}

	@Override
	public String execute(){
		try {
			int flag = filterType(allowedTypes.split(","));
			if (flag == 0) {
				statusCode = "300";
				message = "请导入excel文件!";
			} else { 
				Workbook book = createWorkBook(new FileInputStream(excelFile));
				Sheet sheet = book.getSheetAt(0);

				CellStyle cellStyle2 = book.createCellStyle();
				DataFormat format = book.createDataFormat();
				cellStyle2.setDataFormat(format.getFormat("@"));
				List<BrokerageTempDetail> btdList = new ArrayList<BrokerageTempDetail>();
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Row row = sheet.getRow(i);
					row.setRowStyle(cellStyle2);
					BrokerageTempDetail btd = validExcel(row);
					if (btd == null) {
						statusCode = "300";
						return SUCCESS;
					} else {
						btd.setCustomerId(customerId);
						btd.setInsertTime(ObjectUtils.formatDate(null, "yyyy-MM-dd HH:mm:ss"));
						btd.setStatus(ConstantTool.STATUS_OK);
						
						btdList.add(btd);
					}
				}

				if (btdList.size() > 0) {
					SysCommissionBusinessService scbs = new SysCommissionBusinessService();
					String exeStatus = scbs.batchSaveBorkerageTemp(btdList);
					if("SUCCESS".equals(exeStatus)){
						statusCode = "200";
						message = "导入数据成功, 总共导入: " + btdList.size()+" 条!";
					}else{
						statusCode = "300";
						message = "系统繁忙, 导入佣金excel数据失败!";
					}
				} else {
					statusCode = "300";
					message = "佣金Excel没有数据, 导入失败!!";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			statusCode = "300";
			message = "系统异常, 导入佣金excel数据失败!";
		}
		return SUCCESS;
	}

	private BrokerageTempDetail validExcel(Row row) {
		BrokerageTempDetail btd = new BrokerageTempDetail();
		int rowNum = row.getRowNum() + 1;
		//结算账期
		Cell cell0 = row.getCell(0);
		if (null == cell0) {
			message = "第[ " + rowNum + " ]行, 结算账期不能为空!";
			return null;
		}
		String settlementAccount = getCellValue(cell0);
		btd.setSettlementAccount(settlementAccount);
		
		//地市名称
		Cell cell1 = row.getCell(1);
		if (cell1 == null) {
			message = "第[ " + rowNum + " ]行, 地市名称不能为空!";
			return null;
		}
		String cityName = getCellValue(cell1);
		btd.setCityName(cityName);
		
		//入网手机号
		Cell cell2 = row.getCell(2);
		if (null == cell2) {
			message = "第[ " + rowNum + " ]行, 入网手机号不能为空!";
			return null;
		}
		String mobile   = getCellValue(cell2);
		btd.setMobile(mobile);
		
		//产品唯一码栏
		Cell cell3 = row.getCell(3);
		if (null == cell3) {
			message = "第[ " + rowNum + " ]行, 产品唯一码不能为空!";
			return null;
		} 
		String barCode = getCellValue(cell3);
		btd.setBarCode(barCode);
		
		//入网日期
		Cell cell4 = row.getCell(4);
		if(null == cell4){
			message = "第[ " + rowNum + " ]行, 入网日期不能为空!";
		}
		String netIdTime = getCellValue(cell4);
		if(netIdTime.length() > 19){
			netIdTime = netIdTime.substring(0, 19);
		}
		btd.setNetIdTime(netIdTime);
		
		 //佣金分成值
		Cell cell5 = row.getCell(5);
		if(cell5 == null){
			message = "第[ " + rowNum + " ]行, 佣金分成值不能为空!";
			return null;
		}
		String brokerageMoney = getCellValue(cell5);
		if(!ObjectUtils.isNumber(brokerageMoney)){
			message = "第[ " + rowNum + " ]行, 佣金分成值格式不正确, 请输入数字!";
			return null;
		}
		btd.setBrokerageMoney(brokerageMoney);
	 
		 //入网订单号
		Cell cell6 = row.getCell(6);
		if(cell6 == null){
			message = "第[ " + rowNum + " ]行, 入网订单号不能为空!";
			return null;
		}
		String orderId= getCellValue(cell6);
		btd.setOrderId(orderId);
		
		//销售方式
		Cell cell7 = row.getCell(7);
		if(cell7 == null){
			message = "第[ " + rowNum + " ]行, 销售方式不能为空!";
			return null;
		}
		String salesId = getCellValue(cell7);
		if(!StringUtil.isNumber(salesId)){
			message = "第[ " + rowNum + " ]行, 销售方式格式不正确, 请输入数字!";
			return null;
		}
		btd.setSalesId(Integer.parseInt(salesId));
		
		//入网套餐
		Cell cell8 = row.getCell(7);
		if(cell8 == null){
			message = "第[ " + rowNum + " ]行, 入网套餐不能为空!";
			return null;
		}
		String comboId = getCellValue(cell8);
		if(!StringUtil.isNumber(comboId)){
			message = "第[ " + rowNum + " ]行, 入网套餐格式不正确, 请输入数字!";
			return null;
		}
		btd.setComboId(Integer.parseInt(comboId));
		return btd;
	}
	
	public String getCellValue(Cell cell) {
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		String val = cell.getStringCellValue();
		return val;
	}
	/**
	 * 判断上传的是否为excel; 0: 否; 1: 是.
	 * @param types
	 * @return
	 */
	public int filterType(String[] types) {
		if (null != excelFile) {
			String fileName = excelFileFileName;
			String suffix = "";
			if ((fileName != null) && (fileName.length() > 0)) {
				int dot = fileName.lastIndexOf('.');
				if ((dot > -1) && (dot < (fileName.length() - 1))) {
					suffix = fileName.substring(dot);
				}
			}
			for (String type : types) {
				if (!StringUtil.isNumber(suffix)
						&& type.equalsIgnoreCase(suffix)) {
					return 1;
				}
			}
		}
		return 0;
	}
}
